<template>
  <div class="queue" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other_half_hour" @changeType='changeType' :query="query"  @isFold="isShowFold" :isTimePeriod = "true" :isOther="true"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="skill">
                  <span class="ski">{{$t('public.queues')}}：</span>
                  <el-select size="mini"
                             v-model.trim="query.selectedQueueList"
                             :placeholder="$t('report.queueNaSea')"
                             multiple
                             filterable>
                    <el-option
                      v-for="item in options"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.queueReportRe')"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="options24out"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <el-button class="primary_btn fr formal"  v-if="configFormula" @click="$refs.formulaEditorDialog.open()">{{$t('report.formalTitle')}}</el-button>
          <el-button class="primary_btn fr" v-on:click.stop="config" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            v-on:click.stop="exportExcel"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->
           <el-tooltip class="item" content="点击可导出时间范围下每日的技能组数据。注：当您选择的时间范围超过一个月时，详情只支持导出近一个月的详细数据。" effect="dark" placement="bottom">
              <el-button class="primary_btn fr" style="margin: 0 10px 0 0" v-show="isShowDetailExport" @click.stop="exportXlsxDetail">{{$t('report.exportDetailXls')}}
                <span class="tip"><i class="iconfont icon-tixingweizhi" style="border: none;font-size: 10px;color: #459ae9;"></i></span>
              </el-button>
            </el-tooltip>
          <el-button class="primary_btn fr report_excel_btn"
            v-on:click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy" >
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                <p style="color: #ccc;
    margin: 5px 0;
    font-size: 12px;">{{ $t('report.callSkillHint') }}</p>
                {{$t('report.callConnectNum')}}<br>
                {{$t('report.connectioRate')}}<br>
                {{$t('report.callQueueTotalNum')}}<br>
                {{$t('report.twentySecondPick')}}<br>
                {{$t('report.turnOnaverQueuTime')}}<br>
                {{$t('report.callMaxQueueTime')}}<br>
                {{$t('report.callMinQueueTime')}}<br>
                {{$t('report.giveUpAverQueueTime')}}<br>
                {{$t('report.giveUpMaxQueueTime')}}<br>
                {{$t('report.giveUpMinQueueTime')}}<br>
                {{$t('report.callNotConnect')}}<br>
                {{$t('report.sixSecondGiveUp')}}<br>
                {{$t('report.averCallTime')}}<br>
                {{$t('report.serviceLevel')}}<br>
                15.{{$t('report.callTalkTime')}}<br>
                16.{{$t('report.InOverflowCount')}}<br>
                17.{{$t('report.OutOverflowCount')}}<br>
                18.{{$t('report.TransferSkillGroupCallNumber')}}<br>
                19.{{$t('report.TransferAcceptNumber')}}<br>
                20.{{$t('report.callQueueUpNum1')}}<br>
                <p class="custom_alg">{{$t('report.ziDingYi')}}：</p>
                  <p v-for="(item, index) in formulas" :key="item.name">
                    {{index + 21}}.{{item.formulaInstr}}
                  </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="serveNumData" :sum="sum" :config="[...headOptions.Config,  ...formulasConfig]"> </report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_queue" v-on:close="close" :headCustom="formulasConfig"></header-option>
     <!-- 自定义公式组件 -->
      <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config" @closeFormulaDialog="closeFormulaDialog" reportName="技能组对比报表" :reportType="id"/>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'

  import unfold from '../../../ui-modules/unfold/index.vue'
  import reportTable from '../base/reportTable.vue'
  import dateTime from '../base/datetime.vue'
  import {exportReportPdf, checkTime, searchTime, colorConfigArr, headOptionsToXlsxHeaders,mixData} from '@/utils/reportUtils.js'
  import {getCache, deepClone, getCallTimeLength, optionTimeTypeCheck,isHasFunc} from '@/utils/m7Utils.js'
  import headerOption from '../base/headerOption.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
  import {sortBy} from 'lodash'
  export default {
    name: '',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        isFold: false, // 是否展示搜索条件
        loading: false, // 查询时展示加载的开关
        id: 'call_report_queue', // 查询id
        query: { // 查询条件时间信息等
          selectedQueueList: []
        },
        isShow: false, // 配置表头弹层开关
        options: [], // 技能组渲染数据
        queues: [], // 技能组所有数据
        dialogVisible: false, // 导出pdf开关
        headOptions: { // 表头数据
          Config: []
        },
        dateType:'',
        serveNumData: [], // 渲染表格数据
        headOptionsShow: {}, // 配置表头用的数据
        sum: [], // 合计数据
        sumExclude: ['queue_name', 'AcceptRate', 'AcceptRateNotIn6Leak'], // 合计计算不包含字段集
        chartInclude: ['AcceptAverageQueueTimeLength', 'AcceptMaxQueueTimeLength', 'AcceptMinQueueTimeLength', 'AbandonAverageQueueTimeLength', 'AbandonMaxQueueTimeLength', 'AbandonMinQueueTimeLength', 'AcceptAverageCallInTimeLength'], // charts图表包含字段集
        options24out: { // 图表配置
          chart: {
            type: 'column',
            animation: false
          },
          colors: colorConfigArr,
          xAxis: {
            categories: []
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: {
              text: ''
            }
          },
          title: {
            text: this.$t('report.queueReport')
          },
          legend: {
            align: 'center',
            verticalAlign: 'top',
            x: 0,
            y: 20
          },
          tooltip: {
            formatter: function () {
              var s = '<span style="font-size:10px">' + this.x + '</span><table>'
              let self = this
              self.points.forEach(function (item) {
                var unit = ''
                if (item.series.name.slice(-2) === '时长') {
                  unit = 's'
                } else if (item.series.name.slice(-1) === '率') {
                  unit = '%'
                }
                s += '<tr><td style="color:' + item.series.color + ';padding:0">' + item.series.name + ': </td><td style="padding:0"><b>' + item.y + '' + unit + '</b></td></tr>'
              })
              s += '</table>'
              return s
            },
            shared: true,
            useHTML: true
          },
          plotOptions: {
          },
          credits: {enabled: false},
          series: []
        },
        isSearch:false,
        formulas:[],
        resData:[]
      }
    },
    computed: {
      // 判断是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
       // 是否展示导出详细excel
      isShowDetailExport () {
        let type = ['other_half_hour', 'month','week']
        return type.includes(this.dateType)
      },
       // 自定义表头
      formulasConfig () {
        return this.formulas.map((d, i) => {
          return {
            displayname: d.displayname,
            name: d.name,
            order: d.order,
            show: d.show,
            timeType: 'none',
            digits: d.digits,
            type: d.type
          }
        })
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      headerOption,
      FormulaEditorDialog
    },
    watch: {
      // 监测自定义公式变化 更新数据
      formulas (cur, old) {
        if (this.isSearch) {
          return
        }
        if (!this.serveNumData || this.serveNumData.length === 0) {
          return
        }
        var queryData = this.getSearchQueryData()
        if (!queryData) {
          return
        }
        var {sum, tempData} = this.processDataAndSum(this.resData, this.headOptions, this.queues, this.options24out)
        this.sum = sum
        this.serveNumData = deepClone(mixData(tempData, this.formulas))
      }
    },
    methods: {
      changeType(val){
        console.log(val);
        this.dateType = val
      },
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog () {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 抽出查询条件
      getSearchQueryData () {
        let data = {
          reportType: 'call_report_queue',
          account: this.$store.state.session.user.account
        }
        console.log(this.query);
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = null;
          if (this.dateType === 'week') { // 周报允许到天
            myQuery.timeType = 'other'
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          } else {
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          }
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.selectedQueueList = myQuery.selectedQueueList.join(',')
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.reportType = 'call_report_queue'
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        data['query'] = myQuery
        return data
      },
      // 处理数据和合计
      processDataAndSum (tempData, headOptions, Queue, options24out) {
        var series4high = {}
        var sum = [{queue_name: this.$t('report.total')}]
        for (let i in tempData) {
          let item = tempData[i]
          for (let j in Queue) {
            if (item.QueueID === Queue[j]._id) {
              item.queue_name = Queue[j].DisplayName
            }
          }
          if (!item.queue_name) {
            item.queue_name = ''
          }
          options24out && options24out.xAxis.categories.push(item.queue_name)
          // 计算合计
          for (let j in item) {
            if (sum[0][j] === undefined) {
              sum[0][j] = 0
            }
            if (series4high[j] === undefined) {
              series4high[j] = []
            }
            if (j !== 'queue_name') {
              series4high[j].push(Math.round(item[j]))
            } else {
              delete series4high[j]
            }
            if (this.sumExclude.indexOf(j) < 0) {
              if (!isNaN(item[j])) {
                if ((j in sum[0]) === false) {
                  sum[0][j] = 0
                }
                if (j === 'AcceptMaxQueueTimeLength') {
                  if (item[j] > sum[0][j]) {
                    sum[0][j] = item[j]
                  }
                } else if (j === 'AcceptMinQueueTimeLength') {
                  if (item[j] !== 0) {
                    if (sum[0][j] === 0) {
                      sum[0][j] = item[j]
                    }
                    if (item[j] < sum[0][j]) {
                      sum[0][j] = item[j]
                    }
                  }
                } else if (j === 'AbandonMaxQueueTimeLength') {
                  if (item[j] > sum[0][j]) {
                    sum[0][j] = item[j]
                  }
                } else if (j === 'AbandonMinQueueTimeLength') {
                  if (item[j] !== 0) {
                    if (sum[0][j] === 0) {
                      sum[0][j] = item[j]
                    }
                    if (item[j] < sum[0][j]) {
                      sum[0][j] = item[j]
                    }
                  }
                } else {
                  sum[0][j] += item[j]
                }
              }
            }
          }

          headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getCallTimeLength(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = Math.round(item[option.name]) + 's'
            }
          })
        }
        // 处理合计时间字段
        sum[0].AcceptRateNotIn6Leak =
          sum[0].AccessCount === 0
          ? 0
          : Math.round(
            (sum[0].AcceptCount / (sum[0].AccessCount - sum[0].AbandonIn6SumQueueLeak)) * 100
          ) + '%'
        // 服务水平计算
        sum[0].ServiceLevel = sum[0].AccessCount === 0 ? 0 : Math.round((sum[0].AcceptIn20Count / sum[0].AccessCount) * 10) / 10
        // 平均通话时长计算
        sum[0].AcceptAverageQueueTimeLength = sum[0].AcceptCount > 0 ? Math.round(sum[0].AcceptSumQueueTimeLength / sum[0].AcceptCount) : 0
        // 放弃平均排队时长计算
        if (sum[0].AccessCount - sum[0].AcceptCount === 0) {
          sum[0].AbandonAverageQueueTimeLength = 0
        } else {
          sum[0].AbandonAverageQueueTimeLength = Math.round(sum[0].AbandonSumQueueTimeLength / (sum[0].AccessCount - sum[0].AcceptCount))
        }
        // 平均通话时长计算
        sum[0].AcceptAverageCallInTimeLength = sum[0].AcceptCount > 0 ? Math.round(sum[0].AcceptSumCallInTimeLength / sum[0].AcceptCount) : 0
        headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            sum[0][option.name] = getCallTimeLength(sum[0][option.name])
          } else if (option.timeType && option.timeType === 'second') {
            sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
          }
        })
        //接通率小数点设置
        let zero = 0;
        headOptions.Config.forEach((item,index)=>{
          if(item.name == 'AcceptRate'){
            if(item.radixPoint){
              sum[0].AcceptRate = sum[0].AccessCount === 0 ? zero.toFixed(item.radixPoint) : (Math.round((sum[0].AcceptCount / sum[0].AccessCount) * 100)).toFixed(item.radixPoint) + '%'
            }else{
              sum[0].AcceptRate = sum[0].AccessCount === 0 ? 0 : Math.round((sum[0].AcceptCount / sum[0].AccessCount) * 100) + '%'
            }
          }
        })
        sum = mixData(sum, this.formulas)
        return {
          tempData,
          sum,
          series4high
        }
      },
      // 查询方法
      search () {
        var data = this.getSearchQueryData()
        console.log(data);
        if (!data) {
          return
        }
        var myQuery = data.query
        this.loading = true;
        this.isSearch = true
        this.$store.dispatch('queryCallQueueReport', data).then((res) => {
          if (res.queues && res.queues.length) {
            this.queues = deepClone(res.queues)
          }
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp)=>{
             if (resp.success) {
              this.formulas = resp.data.Formulas
              //  如果为定时间段统计，图表标题加入定时段的时间
              let highchartsTitle = ''
              if (myQuery.timePeriod) {
                let timePeriodStartStr = myQuery.timePeriodStart || '00:00'
                let timePeriodEndStr = myQuery.timePeriodEnd || '23:59'
                highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
              }
              this.options24out.title.text = this.$t('report.queueReport') + highchartsTitle
              this.headOptions = optionTimeTypeCheck(res.tableHeader)
              // 渲染ichars图表
              this.options24out.xAxis.categories = [];
              this.resData = res.data;
              // let tempData = deepClone(res.data)
              let tempData = deepClone(mixData(res.data, this.formulas))
              let Queue = deepClone(this.queues)

              var {sum, series4high} = this.processDataAndSum(tempData, this.headOptions, Queue, this.options24out)
              this.sum = sum
              this.serveNumData = tempData
              console.log(this.serveNumData,'this.serveNumData')
              // 渲染ichars图表
              this.options24out.series = []
              let config = res.tableHeader.Config
              for (let i in config) {
                let item = config[i]
                if (this.chartInclude.indexOf(item.name) >= 0) {
                  this.options24out.series.push({
                    name: item.displayname,
                    data: series4high[item.name]
                  })
                }
              }
              this.loading = false
             }
          })
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx () {
        var data = this.getSearchQueryData()

        if (!data) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryCallQueueReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          var headOptions = optionTimeTypeCheck(res.tableHeader)
          let tempData = deepClone(mixData(res.data, this.formulas))
          let Queue = deepClone(this.queues)
          var {sum} = this.processDataAndSum(tempData, headOptions, Queue)
          if (tempData.length === 0) {
            sum = []
          }

          var tableData = tempData.concat(sum)
          // var headers = headOptionsToXlsxHeaders(headOptions.Config)
          var headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.queueReport') + timeStamp)
        })
      },
      exportXlsxDetail(){
        let queryData = this.getSearchQueryData();
        if (!queryData) {
          return
        }
        let data = {
          Method:"exportSkillGroupReportDetails",
          Query:queryData.query
        }
        this.$store.dispatch("exportSkillGroupReport",data).then(res=>{
          console.log(res);
        })
      },
      // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      },
      // 配置表头, 并展示配置表头弹窗
      config () {
        this.$store.dispatch('getReportTableHeader', 'call_report_queue').then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.queueReport') + searchTime(this.query), id: this.id})
      },
      // 导出表格数据执行的方法(后端)
      exportExcel () {
        let myQuery = deepClone(this.query)
        myQuery.selectedQueueList = myQuery.selectedQueueList.join(',')
        if (myQuery.timeType === 'other_half_hour') {
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.reportType = 'call_report_queue'
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'exportReportQueue'
        myQuery.user = this.$store.state.session.user._id
        let data = {
          Method: 'exportReportQueue',
          Query: myQuery
        }
        this.$store.dispatch('exportCallQueueReport', data).then(() => {
        })
      }
    },
    beforeMount () {
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      this.$store.dispatch('getCache', {type: 'queues'}).then(() => {
        this.queues = getCache('queues')
        this.search()
        for (let i in this.queues) {
          let queueItem = this.queues[i]
          let option = {
            value: queueItem._id,
            label: queueItem.DisplayName
          }
          this.options.push(option)
        }
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .tip
    cursor pointer
    display inline-block
    border 1px solid #459ae9
    text-align center
    line-height 16px
    border-radius 50%
    margin 0 0 0 6px
    width 16px
  .formal
    margin-left 10px
  .queue
    .skill
      .el-select
        width 400px
</style>
